<?php
/**
 * Created by PhpStorm.
 * User: 王崇全
 * Date: 2018/3/29
 * Time: 16:11
 */

namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\model\Common;
use app\common\model\Config;
use app\common\model\Img;
use java\JavaBridge;
use think\captcha\Captcha;
use think\facade\Env;
use think\facade\Request;
use think\facade\Session;


class ComController extends BaseController
{

    /**
     * 图片验证码
     * @author 王崇全
     * @date   2019/1/7 12:07
     * @return \think\Response
     */
    public function imgCaptcha()
    {

        //过滤非图片请求
        $accept = Request::header("Accept");
        if (stripos($accept, "image") === false) {
            rj();
        }

        $config  = [
            // 验证码字体大小
            'fontSize' => 60,
            // 设置验证码字符为纯数字
            'codeSet'  => '0123456789',
            // 验证码位数
            'length'   => 4,
            // 关闭验证码杂点
            'useNoise' => false,
            //字体
            'fontttf'  => '1.ttf',
        ];
        $captcha = new Captcha($config);

        return $captcha->entry();
    }

    /**
     * 发送验证码
     * @author 王崇全
     * @date   2019/1/7 12:18
     * @return void
     * @throws \Exception
     */
    public function sendCaptcha()
    {
        $in = $this->I([
            [
                "captcha|图片验证码",
                null,
                "s",
                "require",
            ],
            [
                "type|发送途径",
                null,
                "s",
                "in:1,2",
            ],
            [
                "phone|手机号",
                null,
                "s",
                "mobile",
            ],
            [
                "email|邮箱",
                null,
                "s",
                "email",
            ],

        ]);

        //检测图片验证码
        $common = new Common();
        if (!$common->checkImgCaptcha($in['captcha'])) {
            rj(1, '验证码错误!');
        }

        //发送途径
        $regType = $in['type'];
        if (!$regType) {
            $cfg     = new Config();
            $regType = $cfg->get('reg_method');
        }

        $c = new Common();
        if ($regType == 1) { //手机号

            if (!$in["phone"]) {
                rj(1, "手机号不能为空");
            }

            $c->sendSmsCaptcha($in["phone"]);

            //保存手机号
            Session::set("phone_email", $in["phone"]);
        } else { //邮箱
            if (!$in["email"]) {
                rj(1, "邮箱不能为空");
            }

            $c->sendEmailCaptcha($in["email"]);

            //保存邮箱地址
            Session::set("phone_email", $in["email"]);
        }

        rj();
    }

    /**
     * 获取GUID
     * @author 王崇全
     * @date
     * @return void
     */
    public function uuid()
    {
        //数据接收&校验
        $in = $this->I([
            [
                "count",
                1,
                "d",
                "require|number|<=:50|>:0",
            ],
            [
                "name",
                null,
                "s",
            ],
        ]);

        //生成GUID
        $r = [];
        for ($i = 0; $i < $in["count"]; $i++) {
            $r[] = uuid();
        }

        $count = count($r);
        $r     = $count == 1 ? $r[0] : $r;

        rjd([
            "uuid"  => $r,
            "count" => $count,
        ]);
    }

    /**
     * 上传图片
     * @author 王崇全
     * @date
     * @return void
     * @throws
     */
    public function uplImg()
    {

        if (is_null(UID)) {
            rj(1, "请先登录");
        }

        $res = Img::upload();

        rjd(["path" => $res]);
    }

    /**
     * 心跳包
     * @author 王崇全
     * @date
     * @return void
     */
    public function hp()
    {
        rj();
    }

    /**
     * 显示每日必应壁纸
     * @author 王崇全
     * @date
     * @return void
     */
    public function bgimg()
    {
        //显示图片
        ob_end_clean();
        header('content-type:image/jpg;');
        //缓存一天
        cache_olgt(3600 * 24);

        $filePath = Env::get('runtime_path').'temp/';
        !is_dir($filePath) && mkdir($filePath, 0755, true);

        $file = $filePath."bing.jpg";

        try {
            //每天更新一次
            if (!is_file($file) || time() - filemtime($file) > 3600 * 24) {
                $bingimg = $this->bingImgFetch();
                file_put_contents($file, file_get_contents("http://www.bing.com/".$bingimg['url']));
            }
        } catch (\Exception $e) {
        }

        //备用图片
        if (!is_file($file)) {
            $file = $_SERVER['DOCUMENT_ROOT']."/image/bg/timg.jpg";
        }

        die(file_get_contents($file));
    }

    /**
     * 获取Bing每日壁纸和故事
     * @author giuem
     */
    private function bingImgFetch()
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36',
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $re = curl_exec($ch);
        curl_close($ch);
        $re  = json_decode($re, 1);//电脑版返回内容
        $re2 = json_decode(file_get_contents('http://cn.bing.com/cnhp/coverstory/'), 1);//移动版返回内容

        return [
            /* 更改图片尺寸，减小体积 */
            'url'   => str_replace('1920x1080', '1366x768', $re['images'][0]['url']),
            /* 结束日期 */
            'date'  => date('j', strtotime($re['images'][0]['enddate'])),
            /* 故事标题 */
            'title' => $re2['title'],
            /* 内容 */
            'd'     => $re2['para1'],
        ];
    }

    /**
     * ueditor 上传
     * @author qfsz168
     * @date   2018/9/9 15:57
     * @return void
     */
    public function ueditor()
    {
        //header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
        //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
        date_default_timezone_set("Asia/chongqing");
        error_reporting(E_ERROR);
        ob_end_clean();
        header("Content-Type: text/html; charset=utf-8");

        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "",
            file_get_contents("../extend/ueditor/config.json")), true);
        $action = $_GET['action'];

        $toChange = [
            'imageUrlPrefix',
            'scrawlUrlPrefix',
            'snapscreenUrlPrefix',
            'catcherUrlPrefix',
            'videoUrlPrefix',
            'fileUrlPrefix',
            'imageManagerUrlPrefix',
            'fileManagerUrlPrefix',
        ];

        foreach ($CONFIG as $k => &$v) {
            if (in_array($k, $toChange)) {
                $v = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'];
            }
        }

        switch ($action) {
            case 'config':
                $result = json_encode($CONFIG);
                break;

            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'upload_file':
                $result = include(EXTEND_PATH."ueditor/action_upload.php");
                break;

            /* 列出图片 */
            case 'listimage':

                /* 列出文件 */
            case 'listfile':
                $result = include(EXTEND_PATH."ueditor/action_list.php");
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $result = include(EXTEND_PATH."ueditor/action_crawler.php");
                break;

            default:
                $result = json_encode([
                    'state' => '请求地址出错',
                ]);
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]).'('.$result.')';
            } else {
                echo json_encode([
                    'state' => 'callback参数不合法',
                ]);
            }
        } else {
            echo $result;
        }
        exit;
    }

    /**
     * 发送邮箱验证码
     * @author 王海东
     * @date
     * @return void
     * @throws \Exception
     */
    public function sendEmail()
    {
        $in = $this->I([
            [
                "email|邮箱",
                null,
                "s",
                "require|email",
            ],
        ]);

        $c = new Common();

        if (!$c->sendEmailCaptcha($in['email'])) {
            rj(1, '发送失败');
        }

        rj();
    }

    /**
     * 发送短信验证码
     * @author 王海东
     * @date
     * @return void
     */
    public function sendSms()
    {
        $in = $this->I([
            [
                "phone|手机号",
                null,
                "s",
                "require|mobile",
            ],
        ]);

        $c = new Common();

        if (!$c->sendSmsCaptcha($in['phone'])) {
            rj(1, '发送失败');
        }

        rj();
    }

    /**
     * test
     * @author 王崇全
     * @date   2019/1/21 16:01
     * @return void
     * @throws \Exception
     */
    public function test()
    {

        $jb = new JavaBridge();

        // $jb->open();
        // $id = $jb->logon();

        //        $id = $jb->QueryHistoryData(0, "20180101", "20190202");
        //        $id = $jb->SendOrder(1, 0, "sz600001", 10, 1);
        //        $id = $jb->SendOrder(1, 0, "sz600001", 10, 1);
        $id = $jb->cancelOrder(1, 0);

        rjd($id);

    }
}